package com.jielin.handling.service.material.impl;

import com.alibaba.fastjson.JSON;
import com.jielin.handling.entity.material.MaterialFile;
import com.jielin.handling.entity.material.MaterialType;
import com.jielin.handling.entity.material.MaterialTypeDocument;
import com.jielin.handling.exception.ResultEnum;
import com.jielin.handling.mapper.material.MaterialFileMapper;
import com.jielin.handling.mapper.material.MaterialTypeDocumentMapper;
import com.jielin.handling.mapper.material.MaterialTypeMapper;
import com.jielin.handling.service.material.MaterialTypeDocumentService;
import com.jielin.handling.service.xsky.XskyService;
import com.jielin.handling.util.ConstantUtil;
import com.jielin.handling.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.File;
import java.util.List;

/**
 * @author WR
 */
@Service
@Slf4j
public class MaterialTypeDocumentServiceImpl implements MaterialTypeDocumentService {
    @Autowired
    private MaterialTypeDocumentMapper maTypeDocumentMapper;
    @Autowired
    private MaterialFileMapper mfMapper;
    @Autowired
    private MaterialTypeMapper mtMapper;
    @Autowired
    private XskyService xskyService;

    @Override
    public List<MaterialTypeDocument> findDocumentByMaterialTypeId(String materialtypeid, String documentName) {
        if (StringUtil.isEmpty(materialtypeid)) {
            return null;
        }
        return maTypeDocumentMapper.findDocumentByMaterialTypeId(materialtypeid, documentName);
    }

    @Override
    public MaterialTypeDocument findDocumentById(String documentid) {
        if (StringUtil.isEmpty(documentid)) {
            return null;
        }
        return maTypeDocumentMapper.findDocumentById(documentid);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public int addDocument(MaterialTypeDocument mtd) {
        if (mtd == null) {
            return ResultEnum.FAIL.getCode();
        }
        MaterialType mt = mtMapper.findById(mtd.getMaterialtypeid());
        if (mt == null) {
            return -2;
        }
        // 创建二级文件夹存放路径==》 案件名称-警员id-案件编号/嫌疑人姓名/一级目录名称/二级文件夹名
        String rootpath = mt.getCasename() + "-" + mt.getUploadpoliceid() + "-" + mt.getCasecode() + File.separator
                + mt.getCaseSuspectName() + File.separator + mt.getMaterialtypename() + File.separator
                + mtd.getDocumentname();
        // 设置存放图片文件的路径
        String path = ConstantUtil.FILE_PATH + rootpath;
        File newFile = new File(path);
        if (!newFile.exists()) {
            newFile.mkdirs();
        }

        log.info("addDocument 事务start...");
        int i = ResultEnum.FAIL.getCode();
        try {
            maTypeDocumentMapper.addDocument(mtd);// 添加
            mtMapper.updateMTAddCount(mt.getId()); // 更新count加1
            i = 1;
        } catch (Exception e) {
            log.info("addDocument 事务回滚:{}", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return i;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public int delDocument(String documentid, String materialtypeid) {
        if (StringUtil.isEmpty(documentid) || StringUtil.isEmpty(materialtypeid)) {
            return ResultEnum.FAIL.getCode();
        }
        List<MaterialFile> list = mfMapper.findFileByDocumentId(documentid, "");// 查询该文件下是否还有文件
        if (list.size() > 0) {
            return -2;
        }
        log.info("delDocument 事务start...");
        int i = ResultEnum.FAIL.getCode();
        try {
            String[] documentids = documentid.split(",");
            log.info("String[] documentids==>" + JSON.toJSONString(documentids));
            for (String id : documentids) {
                if (StringUtil.isEmpty(id)) {
                    continue;
                }
                maTypeDocumentMapper.updateIsDeleteDocument(id);// 更新状态为已删除
                mtMapper.updateMTDelCount(materialtypeid); // 更新count减1
            }

            i = 1;
        } catch (Exception e) {
            log.info("delDocument 事务回滚:{}", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return i;
    }

    @Override
    public int updateDocAddCount(MaterialTypeDocument document) {
        return maTypeDocumentMapper.updateDocAddCount(document.getId());
    }

    @Override
    public int updateDocDelCount(MaterialTypeDocument document) {
        return maTypeDocumentMapper.updateDocDelCount(document.getId());
    }

    @Override
    public int addDocument2(MaterialTypeDocument mtd) {
        MaterialType mt = mtMapper.findById(mtd.getMaterialtypeid());
        if (mt == null) {
            return -2;
        }
        // 创建二级文件夹存放路径==》 案件名称-警员id-案件编号/嫌疑人姓名/一级目录名称/二级文件夹名
        String rootpath = mt.getCasename() + "-" + mt.getUploadpoliceid() + "-" + mt.getCasecode() + File.separator
                + mt.getCaseSuspectName() + File.separator + mt.getMaterialtypename() + File.separator
                + mtd.getDocumentname();
        // 设置存放图片文件的路径
        String path = ConstantUtil.FILE_PATH + rootpath + File.separator;
        try {
            // 兼容win
            path = path.replace("\\", "/");
            xskyService.uploadObject(ConstantUtil.XSKY_BUCKET_DOSSIER, path, "");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("xsky上传文件夹失败！");
        }

        int i = ResultEnum.FAIL.getCode();
        try {
            // 添加文件夹信息
            maTypeDocumentMapper.addDocument(mtd);
            // 更新count加1
            mtMapper.updateMTAddCount(mt.getId());
            i = 1;
        } catch (Exception e) {
            log.info("RecordDetailedService 事务回滚:{}", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return i;
    }
}
